package cn.stronglink.assetmanage;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wx.roundimageview.RoundImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.stronglink.assetmanage.business.check.model.CheckModel;
import cn.stronglink.assetmanage.business.inspection.model.PatrolModel;
import cn.stronglink.assetmanage.business.inspection.model.RepairModel;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.DaoSession;
import cn.stronglink.assetmanage.dao.UserDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.BaseData;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Cabinet;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.DataCenter;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.entity.UserOnLine;
import cn.stronglink.assetmanage.utils.MD5Encrypt;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.base.BaseDataService;
import cn.stronglink.netrequest.business.user.LoginService;
import cn.stronglink.netrequest.util.HttpURL;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author zww
 * 2018 2018/6/17 16:40
 */
public class LoginActivity extends AppCompatActivity {
    private static final String KEY_USERNAME = "userName", KEY_PASSWORD = "userPassword";
    @BindView(R.id.etLoginName)
    EditText loginName;
    @BindView(R.id.etLoginPwd)
    EditText loginPwd;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.rbLocal)
    RadioButton rbLocal;
    @BindView(R.id.rbOnLine)
    RadioButton rbOnLine;
    @BindView(R.id.imgBaseSync)
    RoundImageView imgBaseSync;
    @BindView(R.id.remPwd)
    CheckBox remPwd;
    LoginService service;
    BaseDataService baseDataService;
    Dialog mDialog;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        service = new LoginService();
        baseDataService = new BaseDataService();
        mDialog = CustomProgressDialog.createLoadingDialog(this, "正在加载中...");
        mDialog.setCancelable(false);
        if (DaoManager.getDaoSession(getApplicationContext()).getServerIpDao().queryBuilder().count() > 0) {
            HttpURL.setNewHost(DaoManager.getDaoSession(getApplicationContext()).getServerIpDao().queryBuilder().unique().getIpAddress());
        }
        showUserInfo();
    }

    private void showUserInfo() {
        loginName.setText(PrefUtils.getString(KEY_USERNAME, "", this));
        if (remPwd.isChecked()) {
            loginPwd.setText(PrefUtils.getString(KEY_PASSWORD, "", this));
        } else {
            loginPwd.setText("");
        }
    }

    @OnClick(R.id.imgBaseSync)
    public void setImgBaseSync() {
        Animation circleInim = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
        LinearInterpolator interpolator = new LinearInterpolator();
        circleInim.setInterpolator(interpolator);
        imgBaseSync.startAnimation(circleInim);
        if (null != baseDataService) {
            try {
                baseDataService.getBaseData(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgBaseSync.clearAnimation();
                            }
                        });
                        ToastUtil.toastShort(e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgBaseSync.clearAnimation();
                            }
                        });
                        String json = response.body().string();
                        Result<BaseData> result = null;
                        result = gson.fromJson(json, new TypeToken<Result<BaseData>>() {
                        }.getType());
                        if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                            if (result.getData() != null) {
                                // 保存数据
                                saveBaseData(result.getData());
                            }
                        }
                        ToastUtil.toastShort("基础数据同步成功!");
                    }
                });
            } catch (Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imgBaseSync.clearAnimation();
                    }
                });
                ToastUtil.toastShort("请重试!");
            }
        }
    }

    private void saveBaseData(BaseData baseData) {
        if (baseData == null) {
            return;
        }
        DaoSession session = DaoManager.getDaoSession(LoginActivity.this);

        // 数据中心
        List<DataCenter> dataCenterList = baseData.getDataCenterList();
        if (dataCenterList != null && dataCenterList.size() > 0) {
            session.getDataCenterDao().deleteAll();
            session.getDataCenterDao().insertInTx(dataCenterList);
        }

        // 地点
        List<Room> roomList = baseData.getRoomList();
        if (roomList != null && roomList.size() > 0) {
            session.getRoomDao().deleteAll();
            session.getRoomDao().insertInTx(roomList);
        }

        // 品牌
        List<Brand> brandList = baseData.getBrandList();
        if (brandList != null && brandList.size() > 0) {
            session.getBrandDao().deleteAll();
            session.getBrandDao().insertInTx(brandList);
        }

        // 类型
        List<Type> typeList = baseData.getTypeVo();
        if (typeList != null && typeList.size() > 0) {
            session.getTypeDao().deleteAll();
            session.getTypeDao().insertInTx(typeList);
        }

        // 型号
        List<Model> modelList = baseData.getModelList();
        if (modelList != null && modelList.size() > 0) {
            session.getModelDao().deleteAll();
            session.getModelDao().insertInTx(modelList);
        }

        // 部门
        List<Department> departmentList = baseData.getDepartmentList();
        if (departmentList != null && departmentList.size() > 0) {
            session.getDepartmentDao().deleteAll();
            session.getDepartmentDao().insertInTx(departmentList);
        }

        // 用户
        List<User> userList = baseData.getUserList();
        if (userList != null && userList.size() > 0) {
            session.getUserDao().deleteAll();
            session.getUserDao().insertInTx(userList);
        }
        //机柜
        List<Cabinet> cabinetList = baseData.getCabinetList();
        if (cabinetList != null && cabinetList.size() > 0) {
            session.getCabinetDao().deleteAll();
            session.getCabinetDao().insertInTx(cabinetList);
        }
    }

    @OnClick(R.id.btnLogin)
    public void login() {
        if ("".equals(loginName.getText().toString())) {
            ToastUtil.toastShort("用户名不能为空!");
            return;
        }
        if ("".equals(loginPwd.getText().toString())) {
            ToastUtil.toastShort("密码不能为空!");
            return;
        }
        if ("admin".equals(loginName.getText().toString()) && "admin87654321".equals(loginPwd.getText().toString())) {
            User user = User.getInstance();
            user.setAccount("admin");
            user.setName("admin");
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            this.startActivity(intent);
            finish();
            return;
        }

        if (null != service) {
            if (rbOnLine.isChecked()) {
                try {
                    mDialog.show();
                    service.login(loginName.getText().toString(), loginPwd.getText().toString(), new Callback() {
                        @Override
                        public void onFailure(@NonNull Call request, @NonNull IOException e) {
                            mDialog.cancel();
                            ToastUtil.toastShort("抱歉,登陆失败!");
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            mDialog.cancel();
                            String json = response.body().string();
                            UserOnLine result = null;
                            result = gson.fromJson(json, new TypeToken<UserOnLine>() {
                            }.getType());
                            if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                                ToastUtil.toastShort("登陆成功!");
                                User user = User.getInstance();
                                user.setAccount(result.getUser().getAccount());
                                user.setName(result.getUser().getName());
                                user.setId_(result.getUser().getId_());
                                PrefUtils.putString(KEY_USERNAME, loginName.getText().toString(), LoginActivity.this);
                                PrefUtils.putString(KEY_PASSWORD, loginPwd.getText().toString(), LoginActivity.this);
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                ToastUtil.toastShort("登陆失败!");
                            }
                        }
                    });
                } catch (Exception e) {
                    ToastUtil.toastShort("请稍后重试!");
                    mDialog.cancel();
                }
            } else {
                String userName = loginName.getText().toString();
                List<User> userList = DaoManager.getDaoSession(LoginActivity.this).getUserDao().queryBuilder().where(UserDao.Properties.Account.eq(userName)).list();
                if (null != userList && userList.size() > 0) {
                    if (MD5Encrypt.encrypt(loginPwd.getText().toString()).equals(userList.get(0).getPassword())) {
                        User user = User.getInstance();
                        user.setId_(userList.get(0).getId_());
                        user.setAccount(userList.get(0).getAccount());
                        user.setPassword(userList.get(0).getPassword());
                        user.setName(userList.get(0).getName());
                        PrefUtils.putString(KEY_USERNAME, userName, LoginActivity.this);
                        PrefUtils.putString(KEY_PASSWORD, loginPwd.getText().toString(), LoginActivity.this);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtil.toastShort("密码错误!");
                    }
                } else {
                    ToastUtil.toastShort("用户不存在!");
                }
            }
        }

    }

    private void getPatrolData() {
        final PatrolModel patrolModel = new PatrolModel();
        patrolModel.getRepairData();
        patrolModel.setOnRepairDataListener(new PatrolModel.onPatrolDataListener() {

            @Override
            public void onFailure(Call call, IOException ex) {
                Toast.makeText(LoginActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    if (response.code() == 200) {
                        String json = null;
                        try {
                            json = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (json != null && !"".equals(json)) {
                            patrolModel.savePatrolData(json);
                        }
                    }
                }
            }
        });

    }

}
